package com.daidai.sink.mysqlsink;

import com.daidai.sink.domain.User;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class MyMySqlSink extends RichSinkFunction<User> {

    private Connection connection = null;
    private PreparedStatement prepareStatement = null;

    @Override
    public void open(Configuration parameters) throws Exception {
        connection = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/flink",
                "root",
                "000000"
        );
        String sql = "insert into user values(?, ?, ?)";
        prepareStatement = connection.prepareStatement(sql);
    }

    @Override
    public void invoke(User value, Context context) throws Exception {
        prepareStatement.setInt(1, value.getId());
        prepareStatement.setString(2, value.getUsername());
        prepareStatement.setString(3, value.getPassword());
        prepareStatement.execute();
    }

    @Override
    public void close() throws Exception {
        if (prepareStatement != null) {
            prepareStatement.close();
        }
        if (connection != null) {
            connection.close();
        }
    }


}
